const db = require("../db")
const { querySql , queryOne }=require("../db");






function addArticle(data){//新增帖子
   return db.insert(data,'fs_article',true)   
}


function addTemplate(data){//新增模板
    return db.insert(data,'fs_template')   
}


async function getArticleList(data){//获取帖子列表
    await getTopArticle()
    const offset = (data.page - 1) * data.limit;
    let bookSql = `select u.avatar,u.nickname,u.isvip,a.updated_at,a.isTop,a.id,a.imgs,a.content,a.title from fs_article as a join fs_user as u on a.uid = u.id where a.state='2' order by a.isTop='1' desc, a.updated_at desc`
    bookSql = `${bookSql} limit ${data.limit} offset ${offset}`
    var articleList = await db.querySql(bookSql)
    return articleList
}

async function getSearchArticleList(data){//获取搜索帖子列表
    await getTopArticle()
    const {
        category_id,//分类
        title,//文章
        state = 2 ,//状态
        sort,//排序
        page = 1,
        limit = 20
    } = data

    const offset = (page - 1) * limit;
    let bookSql = `select u.avatar,u.nickname,u.isvip,a.updated_at,a.isTop,a.id,a.imgs,a.content,a.title from fs_article as a join fs_user as u on a.uid = u.id `
    let where = 'where'
    state && (where = db.and(where,'state',2))
    category_id && (where = db.and(where,'category_id',category_id))
    title && (where = db.andLikeTile(where,'title',title))

    if (where !== 'where') {
        bookSql = `${bookSql} ${where}`
    }
    if (sort) {
        var sortitem;
        if(sort==1){
            sortitem = 'updated_at'
        }
        if(sort==2){
            sortitem = 'reading_number'
        }
        if(sort==3){
            sortitem = 'updated_at'
        }

        bookSql = `${bookSql} order by a.isTop='1' desc, ${sortitem} desc`
    }
    bookSql = `${bookSql} limit ${limit} offset ${offset}`
    return await querySql(bookSql)
}


function getMyCollect(data){//获取收藏列表
    const offset = (data.page - 1) * data.limit;
    let bookSql = `select c.is_collect,c.updated_at,a.id,a.imgs,a.content,a.title from fs_article as a join fs_collectlist as c on a.id = c.aid where c.is_collect='1' and c.uid= '${data.uid}' and a.state= '2' `
    bookSql = `${bookSql} order by updated_at desc`
    bookSql = `${bookSql} limit ${data.limit} offset ${offset}`
    return querySql(bookSql)
}


function getMyHistory(data){//获取足迹列表
    const offset = (data.page - 1) * data.limit;
    let bookSql = `select h.updated_at,a.id,a.imgs,a.content,a.title from fs_article as a join fs_historylist as h on a.id = h.aid where  h.uid= '${data.uid}' and a.state= '2' `
    bookSql = `${bookSql} order by updated_at desc`
    bookSql = `${bookSql} limit ${data.limit} offset ${offset}`
    return querySql(bookSql)
}




async function getMyArticleList(data){//获取我的帖子列表
    await getTopArticle()
    const {
        id,//发布人id
        title,//文章
        state,//状态
        page = 1,
        limit = 20
    } = data

    const offset = (page - 1) * limit;
    let bookSql = `select * from fs_article`
    let where = 'where'
    state && (where = db.and(where,'state',state))
    id && (where = db.and(where,'uid',id))
    title && (where = db.andLikeTile(where,'title',title))
    if (where !== 'where') {
        bookSql = `${bookSql} ${where}`
    }
    bookSql = `${bookSql} order by updated_at desc`
    bookSql = `${bookSql} limit ${ limit } offset ${offset} `
  
    return await querySql(bookSql)
}


function getUserArticleList(data){//获取用户的帖子列表

    const {
        uid,//发布人id
        page = 1,
        limit = 20
    } = data

    const offset = (page - 1) * limit;
    let bookSql = `select u.avatar,u.nickname,u.isvip,a.updated_at,a.id,a.imgs,a.content,a.title from fs_article as a join fs_user as u on a.uid = u.id where a.uid=${uid} and a.state=2`
    bookSql = `${bookSql} order by a.updated_at desc`
    bookSql = `${bookSql} limit ${ limit } offset ${offset} `
  
    return querySql(bookSql)
}





async function getArticle(data){//查询帖子详情
   if(data.uid){
        console.log("吐了1",data.uid)
        const collect =  await queryOne(`select is_collect from fs_collectlist  where uid='${data.uid}' and aid='${data.id}'`)
        var  article =  await queryOne(`select a.*,u.nickname,u.avatar from fs_article as a join fs_user as u on a.uid = u.id where a.id='${data.id}'`)
        const relation =  await queryOne(`select relation_type from fs_user_relation  where user_id='${data.uid}' and follower_id='${article.uid}'`)
        console.log("吐了",data.uid,article.uid)
        if(relation==null){
            article.relation_type='0'
        }else{
            article.relation_type=relation.relation_type
        }
        if(collect==null){
            article.is_collect='0'
            return article
        }else{
            article.is_collect=collect.is_collect
            return article
        }
   }else{
    return queryOne(`select a.*,u.nickname,u.avatar from fs_article as a join fs_user as u on a.uid = u.id where a.id='${data.id}'`)
   } 
}

function updateTemplate(data){//更新用户模板
    var data2 = data
    delete data2.state;
    data2.id = data2.template_id
    delete data.template_id;
    return db.update(data2,'fs_template',`where uid='${data2.uid}' and id='${data2.id}'`)
}


async function updateCollect(data){//更新收藏
    const collect =  await queryOne(`select is_collect from fs_collectlist  where uid='${data.uid}' and aid='${data.aid}'`)
    if(collect==null){//如果收藏表没有该收藏就添加
        return db.insert(data,'fs_collectlist')
    }else{
        return db.update(data,'fs_collectlist',`where uid='${data.uid}' and aid='${data.aid}'`)
    }
}


async function updateHistory(data){//更新足迹
    const collect =  await queryOne(`select * from fs_historylist  where uid='${data.uid}' and aid='${data.aid}'`)
    if(collect==null){//如果足迹表没有该足迹就添加
        return db.insert(data,'fs_historylist')
    }else{
        console.log("我进了")
        
        return db.update(data,'fs_historylist',`where uid='${data.uid}' and aid='${data.aid}'`)
    }
}




function getArticleReject(data){//查询帖子驳回原因
    return queryOne(`select * from fs_reject where aid='${data.id}'`)
}


function updataArticle(data){//修改帖子
    return  new Promise( async (resolve,reject)=>{
        try{
            await db.update(data,'fs_article',`where id='${data.id}'`)
            resolve()
         }catch(e){
             reject()
         }
   })
}



function getCategoryList(data){//查询所有分类
    return querySql(`select * from fs_category`)
}


function getTemplate(data){//查询用户的模板
    return querySql(`select * from fs_template where uid='${data.uid}' order by updated_at desc`)
}



function removeArticle(data){
    return  new Promise( async (resolve,reject)=>{
        try{
            if(data.id){
                const removeBookSql = `delete from fs_article where id='${data.id}'`
                await db.querySql(removeBookSql)
                resolve()
            }
        }catch(e){
            reject()
        }
    
   })
}


async function removeTemplate(data){//删除模板
    if(data.id){
        const removeBookSql = `delete from fs_template where id='${data.id}'`
        await db.querySql(removeBookSql)
        resolve()
    }
}

async function setTopArticle(data){//设置帖子置顶
        var article = await db.queryOne(`select isTop,end_time from fs_article where id='${data.id}'`)
        if(article.isTop==0){//如果此帖子没置顶
            data.end_time = addDate('',Number(data.end_time))
            await db.update(data,'fs_article',`where id='${data.id}'`)
            return
        }else if(article.isTop==1){
            data.end_time = addDate(article.end_time,Number(data.end_time))
            await db.update(data,'fs_article',`where id='${data.id}'`)
            return
        }    
}



 function getTopArticle(){//检查置顶帖子时间有没有过期
    return  new Promise( async (resolve,reject)=>{
        try{
            var article =  await db.querySql(`select id,isTop,end_time from fs_article where  isTop='1'`)
            article.forEach(async (item,index)=>{
                if(new Date() > new Date(item.end_time)){
                    await db.update({isTop:0,end_time:null},'fs_article',`where id='${item.id}'`)
                }
            })
            resolve()
        }catch(e){
            reject()
        }
   })
    

}


function addDate(end_time,days){
	if(days == undefined || days == '') {
		days = 1;
	}
    var date = ''
    if(end_time!=''&&end_time!=null){
        date = new Date(end_time);
    }else{
        date = new Date();
    }
	date.setDate(date.getDate() + days);
	var month = date.getMonth() + 1;
	var day = date.getDate();
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var mm = "'" + month + "'";
	var dd = "'" + day + "'";
	//单位数前面加0
	if(mm.length == 3) {
		month = "0" + month;
	}
	if(dd.length == 3) {
		day = "0" + day;
	}
	var time = date.getFullYear() + "-" + month + "-" + day+ " " + hours + ":" + minutes;
	return time;
}



module.exports = {
    getArticleList,
    getCategoryList,
    addArticle,
    getArticle,
    updataArticle,
    getMyArticleList,
    getArticleReject,
    updateCollect,
    getMyCollect,
    getSearchArticleList,
    updateHistory,
    getMyHistory,
    removeArticle,
    addTemplate,
    getTemplate,
    updateTemplate,
    removeTemplate,
    getUserArticleList,
    setTopArticle
}